package com.googlecode.cswish.struts.hibernate;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class SiteClassLoader extends ClassLoader {
	
	private static final Logger logger = Logger.getLogger(SiteClassLoader.class);
	
	private URLClassLoader libClassLoader;

	public SiteClassLoader(String siteName, String path, ClassLoader parent) {
		super(parent);
		
		File classDir = new File(path);
		List<URL> urls = new ArrayList<URL>(1);
		try {
			URL url = classDir.toURI().toURL();
			urls.add(url);
		} catch (MalformedURLException ex) {
			logger.error("invalidd url", ex);
		}
		this.libClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), parent);
		// FIXME: support spring instance & hibernate model object?
	}
	
	public URLClassLoader getLibClassLoaderNoParent() {
		return new URLClassLoader(libClassLoader.getURLs(), null);
	}
	
	public URLClassLoader getLibClassLoader() {
		return this.libClassLoader;
	}

	@Override
	public Class<?> findClass(String name) throws ClassNotFoundException {
		if (libClassLoader == null) {
			throw new ClassNotFoundException(name);
		} else {
			// try to load from current site directory
			return libClassLoader.loadClass(name);
		}
	}
	
	@Override
	protected URL findResource(String name) {
		if (libClassLoader == null) {
			return null;
		} else {
			URL url = libClassLoader.findResource(name);
			return url;
		}
	}
}